package com.ltu.m7011e.imagine.arithmetics.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ltu.m7011e.imagine.arithmetics.client.ArithmeticsService;

public class ArithmeticsServiceImpl extends RemoteServiceServlet implements ArithmeticsService
{
	private char operator = '+';
	private int first = 0;
	private int second = 0;
	
	@Override
	public String getQuestion(String question)
	{
		boolean success = false;
		String message;
		String[] split = question.split(",");
		
		if(split[0].compareTo("start") == 0)
		{
			// TODO - a new game.
			message = "question," + createQuestion();
		}
		else if(split[0].compareTo("answer") == 0)
		{
			if(first + second == Integer.parseInt(split[1]))
			{
				success = true;
			}
			
			// TODO - handle the answer.
			message = "question," + createQuestion() + ","+success;
		}
		else
		{
			message = "error,'" + question + "'";
		}
		
		return message;
	}
	
	private int random(int start, int end)
	{
		double dEnd = 1.0 * end;
		
		return (int)(dEnd * Math.random()) + start;
	}
	
	private String createQuestion()
	{
		// TODO - save the question to check the answer.
		first = random(1, 10);
		second = random(1, 10);
		
		return first + " " + operator + " " + second + " = ";
	}
}
